import { get } from './base'
import storage from 'good-storage'
import MusicList from 'components/music-list/music-list'
export function processSongs(songs) {
    if (!songs.length) {
        return Promise.resolve(songs)
    }

    return get('/api/getSongsUrl', {
        mid: songs.map((song) => {
            return song.mid
        })
    }).then((result) => {
        const map = result.map
        return songs.map((song) => {
            song.url = map[song.mid]
            return song
        }).filter((song) => {
            return song.url && song.url.indexOf('vkey') > -1
        })
    })
}

const lyricMap = {}

export function getLyric(song) {
    if (song.lyric) {
        return Promise.resolve(song.lyric)
    }
    const mid = song.mid
    const lyric = lyricMap[mid]
    if (lyric) {
        return Promise.resolve(lyric)
    }

    return get('/api/getLyric', {
        mid
    }).then((result) => {
        const lyric = result ? result.lyric : '[00:00:00]该歌曲暂时无法获取歌词'
        lyricMap[mid] = lyric
        return lyric
    })
}


export default function createDetailComponent(name, key, fetch) {
    return {
        name,
        components: { MusicList },
        props: {
            data: Object
        },
        data() {
            return {
                songs: [],
                loading: true
            }
        },
        computed: {
            computedData() {
                let ret = null
                const data = this.data
                if (data) {
                    ret = data
                } else {
                    const cached = storage.session.get(key)
                    if (cached && (cached.mid || cached.id + '') === this.$route.params.id) {
                        ret = cached
                    }
                }
                return ret
            },
            pic() {
                const data = this.computedData
                return data && data.pic
            },
            title() {
                const data = this.computedData
                return data && (data.name || data.title)
            }
        },
        async created() {
            const data = this.computedData
            if (!data) {
                const path = this.$route.matched[0].path
                this.$router.push({
                    path
                })
                return
            }
            const result = await fetch(data)
            this.songs = await processSongs(result.songs)
            this.loading = false
        }
    }
}
